package com.atguigu.consumer.api;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.consumer.api.blockHandler.UserBlockHandler;
import com.atguigu.consumer.api.fallback.UserFallback;
import com.atguigu.consumer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 郑启
 * @date 2021/05/13 14:32
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserApi {
	@Autowired
	private UserService userService;

	@SentinelResource(value = "/user/getProfile", blockHandler = "getProfileBlock", fallback = "getProfileFallback")
	@GetMapping(value = "/getProfile", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
	public String getProfile() {
		return userService.getProfile();
	}

	public String getProfileBlock(BlockException ex) {
		log.error("getProfile 方法异常：", ex);
		return "getProfile 方法异常";
	}

	public String getProfileFallback(Throwable e) {
		log.error("服务异常：", e);
		return "user.getProfile 服务繁忙，请稍后再试";
	}

	@SentinelResource(value = "/user/getTimeout", blockHandlerClass = UserBlockHandler.class, blockHandler = "getTimeout", fallbackClass = UserFallback.class, fallback = "getTimeout")
	@GetMapping(value = "/getTimeout", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
	public String getTimeout() {
		return userService.getTimeout();
	}

	@SentinelResource(value = "/user/getDivide", blockHandlerClass = UserBlockHandler.class, blockHandler = "getDivide", fallbackClass = UserFallback.class, fallback = "getDivide")
	@GetMapping(value = "/getDivide", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
	public String getDivide(@RequestParam int divisor) {
		return userService.getDivide(divisor);
	}

	@SentinelResource(value = "/user/getConfigInfo", blockHandlerClass = UserBlockHandler.class, blockHandler = "getConfigInfo", fallbackClass = UserFallback.class, fallback = "getConfigInfo")
	@GetMapping(value = "/getConfigInfo", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
	public String getConfigInfo() {
		return userService.getConfigInfo();
	}
}
